package com.glodon.paas.account.sdk.sso.web;

import com.glodon.paas.account.api.sso.web.AuthenticatedSessionRegistry;
import com.glodon.paas.account.api.sso.web.InMemoryAuthenticatedSessionRegistry;
import org.jasig.cas.client.validation.Assertion;

import javax.servlet.http.HttpSessionAttributeListener;
import javax.servlet.http.HttpSessionBindingEvent;

/**
 * Hold the authenticated sessions for sso clients
 *
 * @author Don Li
 */
public class AuthenticatedSessionClientListener implements HttpSessionAttributeListener {
    private static final AuthenticatedSessionRegistry registry = new InMemoryAuthenticatedSessionRegistry();

    /**
     * Invalidate all the sessions belong to the user
     *
     * @param id user id
     */
    public static void invalidateUserSessions(String id) {
        registry.invalidateUserSessions(id);
    }

    @Override
    public void attributeAdded(HttpSessionBindingEvent se) {
        if (getAttributeName().endsWith(se.getName())) {
            Assertion assertion = (Assertion) se.getValue();
            String userId = assertion.getPrincipal().getName();
            registry.addSession(userId, se.getSession());
        }
    }

    @Override
    public void attributeRemoved(HttpSessionBindingEvent se) {
        if (getAttributeName().endsWith(se.getName())) {
            Assertion assertion = (Assertion) se.getValue();
            String userId = assertion.getPrincipal().getName();
            registry.removeSession(userId, se.getSession());
        }
    }

    @Override
    public void attributeReplaced(HttpSessionBindingEvent se) {
        if (getAttributeName().endsWith(se.getName())) {
            Assertion assertion = (Assertion) se.getValue();
            String userId = assertion.getPrincipal().getName();
            registry.addSession(userId, se.getSession());
        }
    }

    protected String getAttributeName() {
        return AbstractCasSingleSignOnFilter.CAS_ASSERTION;
    }
}
